package com.hmall.item.web;



import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.item.ThreadLocal.LoginThreadLocal;
import com.hmall.item.contants.MqConstants;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.PageDTO;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("item")
public class ItemController {


    @Autowired
    private IItemService itemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> findItemListByPage(@RequestParam("page") Integer page,
                                            @RequestParam("size") Integer size) {
        Page<Item> iPage = new Page<>(page, size);
        Page<Item> page1 = itemService.page(iPage);
        long total = page1.getTotal();
        List<Item> records = page1.getRecords();
        PageDTO<Item> pageDTO = new PageDTO<>();
        pageDTO.setTotal(total);
        pageDTO.setList(records);

        return pageDTO;
    }

    ;

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item queryById(@PathVariable Long id) {
        Item item = itemService.getById(id);


        return item;
    }

    /**
     * 添加商品
     *
     * @param item
     */
    @PostMapping
    public void insertItem(@RequestBody Item item) {
        boolean save = itemService.save(item);
    }

    /**
     * 修改商品上下架状态
     *
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void updateItemStatus(@PathVariable Long id,
                                 @PathVariable Integer status) {
        LambdaUpdateWrapper<Item> uw = new LambdaUpdateWrapper<>();
        uw.eq(Item::getId, id);
        uw.set(Item::getStatus, status);
        if (status == 1){
            rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_STATUS_UP_KEY,id);
        }else if (status == 2){
            rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE,MqConstants.ITEM_STATUS_DOWN_KEY,id);

        }
        itemService.update(uw);

    }

    @PutMapping
    public void updateItem(@RequestBody Item item) {
        itemService.updateById(item);
    }


    @DeleteMapping("/{id}")
    public void deleteItemById(@PathVariable Long id) {
        itemService.removeById(id);
    }


}
